//路由
const express = require("express");
const moment = require("moment");
const db = require("../core/DBHelper");
//创建路由
const apiRoutes = express.Router();
//给路由安排管理任务
apiRoutes.post("/login", async (request, response, next) => {
    const userObj = request.body;
    let sqlLogin = "SELECT `u_name`,`u_phone`,`u_email`,`u_status` FROM userinfo WHERE `u_name`=? AND `u_pwd`=? AND `u_status`=1;"
    let params = [
        userObj.uname,
        userObj.upwd
    ]
    try {
        let res = await db.exec(sqlLogin, params);
        const result = { msg: "登陆失败", code: 200 }
        if (res && res.length >= 1) {
            result["msg"] = "登陆成功";
            res[0].u_create = moment(res[0].u_create).format("YYYY-MM-DD hh:mm:ss");
            result["data"] = res[0]
        }
        setTimeout(() => response.json(result), 1000);

    } catch (error) {
        response.json({
            msg: "登陆失败",
            code: -200,
            error
        })
    }
})

apiRoutes.post("/reg", async (request, response, next) => {
    const userObj = request.body;
    let sqlLogin = "INSERT INTO `userinfo` (`u_name`,`u_phone`,`u_email`,`u_pwd`,`u_create`)VALUE(?,?,?,?,?);"
    let params = [
        userObj.uname,//用户名
        userObj.uphone,//手机号
        userObj.uemail,//邮箱
        userObj.upwd,//密码
        moment(Date.now()).format("YYYY-MM-DD hh:mm:ss")
    ]
    try {
        let res = await db.exec(sqlLogin, params);
        let isReg = (res && res.affectedRows >= 1);
        let result = {
            msg: isReg ? "注册成功" : "注册失败",
            code: 200
        }
        response.json(result);

    } catch (error) {
        let result = {
            msg: "注册失败",
            code: -200,
            error
        }
        response.json(result)
    }
})

apiRoutes.get("/checkName", async (request, response, next) => {
    let { uname } = request.query;
    let sql = "SELECT *FROM userinfo WHERE u_status =1 AND u_name=? ;";
    let result = await db.exec(sql, [uname]);
    let res = !(result && result.length >= 1);
    //用户名存在,返回false,true可以注册
    response.send(res);
})
module.exports = { apiRoutes };